<?php
/**
 * Created by PhpStorm.
 * User: buddha
 * Date: 2021/6/16
 * Time: 11:07
 */

namespace app\admin\service;


use app\model\ManagerRoleModel;
use app\model\RoleAuthModel;
use app\model\RoleModel;
use think\facade\Db;

class RoleService
{
    /**
     * 平台角色创建
     * @param $data
     * @return bool
     */
    public function save($data) {
        $roleModel = new RoleModel();
        return $roleModel->save($data);
    }

    /**
     * 平台角色查询
     * @param $data
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     */
    public function findAll($data) {
        $roleModel = new RoleModel();
        $list = $roleModel->field('id,name,role_desc')
            ->order('id', 'asc')
            ->paginate($data['list_rows']);
        return $list;
    }

    /**
     * 平台角色编辑
     * @param $id
     * @param $data
     * @return RoleModel
     */
    public function update($id, $data) {
        $roleModel = new RoleModel();
        return $roleModel->where('id', $id)->update($data);
    }

    /**
     * 平台角色删除
     * @param $id
     * @return bool
     */
    public function delete($id) {
        $roleModel = new RoleModel();
        $roleAuthModel = new RoleAuthModel();
        $managerRoleModel = new ManagerRoleModel();
        // 启动事务
        Db::startTrans();
        try {
            $roleModel->where('id', $id)->delete();
            $roleAuthModel->where('role_id', $id)->delete();
            $managerRoleModel->where('role_id', $id)->delete();
            // 提交事务
            Db::commit();
            return 1;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return 0;
        }
    }
}